package com.yanfan.energy.util;

import com.alibaba.fastjson2.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.List;


public class HttpGetUtil {

    public static JSONObject sendGetRequest(String url, String token) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建 HttpGet 实例
            HttpGet request = new HttpGet(url);
            // 添加 Header
            request.addHeader("token", token);
            // 发送请求
            try (CloseableHttpResponse response = httpClient.execute(request)) {
                // 获取响应体
                HttpEntity entity = response.getEntity();
                if (entity!= null) {
                    String responseBody = EntityUtils.toString(entity);
                    //System.out.println(responseBody.toString());
                    return JSONObject.parseObject(responseBody);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static List<String> groupData(ArrayList<String> dataList) {
        List<String> groupedData = new ArrayList<>();
        int size = dataList.size();
        for (int i = 0; i < size; i += 100) {
            StringBuilder groupBuilder = new StringBuilder();
            int endIndex = Math.min(i + 100, size);
            for (int j = i; j < endIndex; j++) {
                groupBuilder.append(dataList.get(j));
                if (j < endIndex - 1) {
                    groupBuilder.append(",");
                }
            }
            groupedData.add(groupBuilder.toString());
        }
        return groupedData;
    }
}
